# -*- coding: utf-8 -*-
"""
Loading data file from Mechanically controlled break junction setup at TUDelft
"""
from scipy import loadtxt, array

def loaddatfile(filename, conv_motorcounts_to_nm = 1., val_to_gapsize = 1.):
    """
    Loading data file from Mechanically controlled break junction setup at TUDelft
    conv_motorcounts_to_nm is the conversion from motorpositionnumber to aprox. gap size
    val_to_gapsize is the conversion from the first axis in the data to aprox. gap size. (val_to_gapsize=aattuation*pushingspeed)
    """
    try:
        inputfile = file(filename)
    except IOError:
        print "Error reading \"%s\"" % filename
        return None, []
    meta = {}
    oldline = ""
    oldline2 = ""
    done = False
    k = 0
    for i in range(30):
        if done:
            i = k
            break
        line = inputfile.readline()
        if line == '@\r\n':
            break
        oldline2 = oldline
        oldline = line
        j = 0
        end = 0
        while (True):
            j = line.find(':', end+1)
            if j == -1:
                break
            end2 = -2 if (line.find(',', j+1) == -1) else line.find(',', j+1)+2
            if 'Comments' == line[end:j]:
                meta['Comments'] = line[end:]
                for k in range(i+1, 30):
                    line = inputfile.readline()
                    if line == '@\r\n':
                        done = True
                        break
                    oldline2 = oldline
                    oldline = line
                    meta['Comments'] += line[end:]
            else:
                meta[line[end:j]] = line[(j+2):end2]
            end = end2

    meta["Motor1"] = oldline2[:-2]
    meta["Motor2"] = oldline[:-2]
    try:
        motor_pos = array([float( meta['Motor1'] if -1==meta['Motor1'].find(':') else 0),
                    float( meta['Motor2'] if -1==meta['Motor2'].find(':') else 0)])
    except ValueError:
        motor_pos = array([0, 0])
        #print "Error in reading of motor position"
    meta["Motor_pos[nm]"] = motor_pos*conv_motorcounts_to_nm
    inputfile.close()
    try:
        dat = loadtxt(filename, skiprows=i+1)
        dat[:,0] = dat[:,0]*val_to_gapsize
    except (ValueError, IOError, IndexError):
        print "Error reading %s" % filename
        dat = array([])
    return meta, dat

        
        